package com.mvcplus.system.controller;

import com.mvcplus.common.controller.BaseController;
import com.mvcplus.common.utils.Datatable;
import com.mvcplus.system.model.DicDictionary;
import com.mvcplus.system.service.IDicDictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * Created by BINGO on 2016/10/28.
 * 数据字典
 */
@Controller
@Scope(value = "prototype")
@RequestMapping("/dic")
public class DictionaryController extends BaseController {

    @Autowired
    private IDicDictionaryService dicService;

    @RequestMapping("/")
    public ModelAndView page(ModelAndView modelAndView) {
        modelAndView.setViewName("system/dic");
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping("/datatable")
    public Object datatable(HttpServletRequest request) {
        Integer draw = 1;
        Map<String, String[]> params = request.getParameterMap();
        for (String attr : params.keySet()) {
            String[] val = params.get(attr);
            if (attr.equals("draw"))
                draw = Integer.parseInt(val[0]);
        }
        Datatable dt = new Datatable(draw + 1, dicService.selectList(null));
        return dt;
    }

    @RequestMapping("/addPage")
    public ModelAndView addPage(ModelAndView modelAndView) {
        modelAndView.setViewName("system/dicAdd");
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping("/save")
    public Object add(DicDictionary dic) {
        DicDictionary d = dicService.selectOne(dic);
        if (d == null) {
            return dicService.insertSelective(dic) ? renderSuccess("添加成功") : renderError("添加失败");
        } else {
            return renderError("编码不能重复");
        }
    }

    @ResponseBody
    @RequestMapping("/delete")
    public Object delete(@RequestParam(required = false, value = "ids[]")List<Long> ids) {
        return dicService.deleteBatchIds(ids) ? renderSuccess("删除成功") : renderError("删除失败");
    }

    @ResponseBody
    @RequestMapping("/get")
    public Object get(Long id){
       return dicService.selectById(id);
    }

    @RequestMapping("/editPage")
    public ModelAndView editPage(ModelAndView modelAndView,Long id) {
        modelAndView.setViewName("system/dicEdit");
        modelAndView.addObject("dic",dicService.selectById(id));
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping("/update")
    public Object update(DicDictionary dic) {
        return dicService.updateSelectiveById(dic)? renderSuccess("修改成功") : renderError("修改失败");
    }


}
